package com.base.server.file.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.base.server.file.pojo.FileInfo;
import com.base.server.file.service.FileInfoService;
import com.monitor.api.ApiInfo;
import com.monitor.api.ApiParam;
import com.monitor.api.ApiRes;
import com.system.comm.controller.BaseRestController;
import com.system.comm.model.Orderby;
import com.system.comm.utils.FrameJsonUtil;
import com.system.comm.utils.FrameStringUtil;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;

/**
 * file_info的Controller
 * @author autoCode
 * @date 2019-07-13 16:27:05
 * @version V1.0.0
 */
@RestController
public class FileInfoController extends BaseRestController {

	private static final Logger LOGGER = LoggerFactory.getLogger(FileInfoController.class);

	@Autowired
	private FileInfoService fileInfoService;
	
	/**
	 * 上传附件
	 * @param request
	 * @return
	 */
	@RequestMapping(name = "fileInfo-新增或修改", value = "/fileInfo/save")
	@ApiInfo(params = {
			@ApiParam(name="文件", code="file", value=""),
			@ApiParam(name="来源系统", code="system", value=""),
			@ApiParam(name="分类", code="type", value=""),
			@ApiParam(name="二级分类", code="typeSecond", value=""),
	}, response = {
			@ApiRes(name="响应码[0成功、-1失败]", code="code", clazz=String.class, value="0"),
			@ApiRes(name="响应消息", code="message", clazz=String.class, value="success"),
			@ApiRes(name="主体内容", code="body", clazz=Object.class, value=""),
	})
	public ResponseFrame upload(HttpServletRequest request, HttpServletResponse response,
			FileInfo fileInfo) {
		ResponseFrame frame = new ResponseFrame();
		LOGGER.info(fileInfo.getSystem() + " - type[" + fileInfo.getType() + "] typeSecond[" + fileInfo.getTypeSecond() + "] 向文件服务上传附件!");
		response.setCharacterEncoding("utf-8");

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		/*try {
			request.setCharacterEncoding("utf-8");
			multipartRequest.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
		}*/
		//获得文件
		MultipartFile multipartFile = multipartRequest.getFile("file");
		frame = fileInfoService.save(multipartFile, fileInfo);
		
		
		/*//获得文件
		MultipartFile multipartFile = multipartRequest.getFile("file");
		//获得原始文件名
		String orgName = multipartFile.getOriginalFilename();
		//String fileId = null;
		String fileExt = orgName.substring(orgName.lastIndexOf(".") + 1, orgName.length());
		String sysName = null;
		//为jpg||png||gif||bmp
		if(FrameStringUtil.isEqualsIcArrSin(fileExt, exts)) {
			InputStream inputStream = null;
			try {
				inputStream = multipartFile.getInputStream();

				String savePath = EnvUtil.projectFilePath();
				//Long dateStr = System.currentTimeMillis();
				String browseDateDir = FrameTimeUtil.parseString(FrameTimeUtil.getTime(), FrameTimeUtil.FMT_YYYY);
				browseDateDir += "/" + FrameTimeUtil.parseString(FrameTimeUtil.getTime(), "MM-dd");
				String dateDir = FrameTimeUtil.parseString(FrameTimeUtil.getTime(), FrameTimeUtil.FMT_YYYY);
				dateDir += File.separator + FrameTimeUtil.parseString(FrameTimeUtil.getTime(), "MM-dd");
				sysName = FrameNoUtil.uuid() + "." + fileExt;
				
				String browseUrl = "/" + fileInfo.getType() + "/";
				String newFilePath = File.separator + fileInfo.getSystem() + File.separator + fileInfo.getType() + File.separator;
				if (FrameStringUtil.isNotEmpty(fileInfo.getTypeSecond())) {
					newFilePath += fileInfo.getTypeSecond() + File.separator;
					browseUrl += fileInfo.getTypeSecond() + "/";
				}
				newFilePath += dateDir + File.separator;
				browseUrl += browseDateDir + "/" + sysName;
				
				FrameFileUtil.createDir(savePath + newFilePath);
				File uploadFile = new File(savePath, newFilePath + sysName);
				multipartFile.transferTo(uploadFile);
				
				fileInfo.setBrowseUrl(browseUrl);
				fileInfo.setSavePath(savePath + newFilePath + sysName);
				Double fileSize = (double) (uploadFile.length() / 1024);
				fileInfo.setFileSize(fileSize);
				fileInfo.setSysName(sysName);
				fileInfo.setOrgName(orgName);
				frame = fileInfoService.save(fileInfo);
			} catch (Exception e) {
				LOGGER.error(e.getMessage(), e);
				frame.setCode(ResponseCode.FAIL.getCode());
			} finally {
				if(inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
						LOGGER.error(e.getMessage(), e);
					}
				}
			}
		} else {
			frame.setCode(-3);
			frame.setMessage("上传文件的格式异常");
		}
		LOGGER.info("上传文件返回结果: " + FrameJsonUtil.toString(fileInfo));*/
		return frame;
	}
	/**
	 * 下载文件
	 * @param request
	 * @param response
	 * @param path
	 * @throws Exception
	 */
	@RequestMapping(value = "/fileInfo/download")
	@ApiInfo(params = {
			@ApiParam(name="地址", code="url", value=""),
	}, response = {
			@ApiRes(name="响应码[0成功、-1失败]", code="code", clazz=String.class, value="0"),
			@ApiRes(name="响应消息", code="message", clazz=String.class, value="success"),
			@ApiRes(name="主体内容", code="body", clazz=Object.class, value=""),
			
	})
	public void download(HttpServletRequest request, HttpServletResponse response, String url) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		LOGGER.info(url + " - 下载文件!");

		FileInfo file = fileInfoService.getByBrowseUrl(url);
		if (file == null) {
			LOGGER.error(url + " - 不存记录!");
			return;
		}
		//String downLoadPath = ctxPath;

		long fileLength = new File(file.getSavePath()).length();
		int separator = url.lastIndexOf(File.separator);
		if(separator == -1) {
			separator = url.lastIndexOf("/");
		}
		response.setHeader("Content-disposition", "attachment; filename=" + new String(file.getOrgName().getBytes("utf-8"), "iso-8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));

		bis = new BufferedInputStream(new FileInputStream(file.getSavePath()));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}
	
	@RequestMapping(name = "fileInfo-获取详细信息", value = "/fileInfo/get")
	@ApiInfo(params = {
			@ApiParam(name="fileId", code="fileId", value=""),
	}, response = {
			@ApiRes(name="响应码[0成功、-1失败]", code="code", clazz=String.class, value="0"),
			@ApiRes(name="响应消息", code="message", clazz=String.class, value="success"),
			@ApiRes(name="主体内容", code="body", clazz=Object.class, value=""),
			
	})
	public ResponseFrame get(String fileId) {
		try {
			ResponseFrame frame = new ResponseFrame();
			frame.setBody(fileInfoService.get(fileId));
			frame.setCode(ResponseCode.SUCC.getCode());
			return frame;
		} catch (Exception e) {
			LOGGER.error("处理业务异常: " + e.getMessage(), e);
			return new ResponseFrame(ResponseCode.SERVER_ERROR);
		}
	}

	@RequestMapping(name = "fileInfo-分页查询信息", value = "/fileInfo/pageQuery")
	@ApiInfo(params = {
			@ApiParam(name="页面", code="page", value="1"),
			@ApiParam(name="每页大小", code="size", value="10"),
			@ApiParam(name="排序[{\"property\": \"createTime\", \"type\":\"desc\", \"order\":1}]", code="orderby", value="", required=false),
	}, response = {
			@ApiRes(name="响应码[0成功、-1失败]", code="code", clazz=String.class, value="0"),
			@ApiRes(name="响应消息", code="message", clazz=String.class, value="success"),
			@ApiRes(name="主体内容", code="body", clazz=Object.class, value=""),
			@ApiRes(name="当前页码", code="page", pCode="body", clazz=Integer.class, value="1"),
			@ApiRes(name="每页大小", code="size", pCode="body", clazz=Integer.class, value="10"),
			@ApiRes(name="总页数", code="totalPage", pCode="body", clazz=Integer.class, value="5"),
			@ApiRes(name="总记录数", code="total", pCode="body", clazz=Integer.class, value="36"),
			@ApiRes(name="数据集合", code="rows", pCode="body", clazz=List.class, value=""),
			@ApiRes(name="编号", code="fileId", pCode="rows", value=""),
			@ApiRes(name="系统名称", code="sysName", pCode="rows", value=""),
			@ApiRes(name="原名称", code="orgName", pCode="rows", value=""),
			@ApiRes(name="来源系统", code="system", pCode="rows", value=""),
			@ApiRes(name="分类", code="type", pCode="rows", value=""),
			@ApiRes(name="保存路径", code="savePath", pCode="rows", value=""),
			@ApiRes(name="访问路径", code="browseUrl", pCode="rows", value=""),
			@ApiRes(name="文件大小", code="fileSize", pCode="rows", value=""),
			@ApiRes(name="上传时间", code="uploadTime", pCode="rows", value=""),
	})
	public ResponseFrame pageQuery(FileInfo fileInfo, String orderby) {
		try {
			if(FrameStringUtil.isNotEmpty(orderby)) {
				List<Orderby> orderbys = FrameJsonUtil.toList(orderby, Orderby.class);
				fileInfo.setOrderbys(orderbys);
			}
			ResponseFrame frame = fileInfoService.pageQuery(fileInfo);
			return frame;
		} catch (Exception e) {
			LOGGER.error("处理业务异常: " + e.getMessage(), e);
			return new ResponseFrame(ResponseCode.SERVER_ERROR);
		}
	}

	@RequestMapping(name = "fileInfo-根据主键删除", value = "/fileInfo/delete")
	@ApiInfo(params = {
			@ApiParam(name="fileId", code="fileId", value=""),
	}, response = {
			@ApiRes(name="响应码[0成功、-1失败]", code="code", clazz=String.class, value="0"),
			@ApiRes(name="响应消息", code="message", clazz=String.class, value="success"),
			@ApiRes(name="主体内容", code="body", clazz=Object.class, value=""),
	})
	public ResponseFrame delete(String fileId) {
		try {
			ResponseFrame frame = fileInfoService.delete(fileId);
			return frame;
		} catch (Exception e) {
			LOGGER.error("处理业务异常: " + e.getMessage(), e);
			return new ResponseFrame(ResponseCode.SERVER_ERROR);
		}
	}


	@RequestMapping(name = "fileInfo-根据主键删除", value = "/fileInfo/getByBrowseUrl")
	@ApiInfo(params = {
			@ApiParam(name="browseUrl", code="browseUrl", value=""),
	}, response = {
			@ApiRes(name="响应码[0成功、-1失败]", code="code", clazz=String.class, value="0"),
			@ApiRes(name="响应消息", code="message", clazz=String.class, value="success"),
			@ApiRes(name="主体内容", code="body", clazz=Object.class, value=""),
	})
	public ResponseFrame getByBrowseUrl(String browseUrl) {
		try {
			ResponseFrame frame = new ResponseFrame();
			FileInfo fileInfo = fileInfoService.getByBrowseUrl(browseUrl);
			frame.setBody(fileInfo);
			frame.setSucc();
			return frame;
		} catch (Exception e) {
			LOGGER.error("处理业务异常: " + e.getMessage(), e);
			return new ResponseFrame(ResponseCode.SERVER_ERROR);
		}
	}
}